package com.paw.hys.sa.config;

import java.util.Map;
import java.util.concurrent.Callable;

import javax.annotation.PostConstruct;

import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.paw.hys.sa.content.ContentHolder;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

/**
 * @author lvzihai
 * @date 2022/8/26
 **/
@Component
public class MyHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {

  @PostConstruct
  public void register(){
    HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
  }

  @Override
  public <T> Callable<T> wrapCallable(Callable<T> callable) {

    String val = ContentHolder.getValue();
    String traceId = ThreadContext.get("traceId");
    Map<String, String> mdcContentMap = MDC.getCopyOfContextMap();
//    System.out.println("MyHystrixConcurrencyStrategy #1 "+Thread.currentThread().getName());
    return () -> {
      ContentHolder.setValue(val);
      ThreadContext.put("traceId",traceId);
      MDC.setContextMap(mdcContentMap);
//      System.out.println("MyHystrixConcurrencyStrategy #2 "+Thread.currentThread().getName());
      try {
        return callable.call();
      } finally {
        ContentHolder.remove();
      }
    };
  }


}
